<?php
session_start();
//session_destroy();exit;

require 'include/config.inc.php';
require 'include/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId'  => FB_API_ID,
'secret' => FB_API_SECRET,
'cookie' => FB_COOKIE,
));

// We may or may not have this data based on a $_GET or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();

$me = null;
// Session based API call.
if ($session) {
	try {
		$uid = $facebook->getUser();
		$me = $facebook->api('/me');
	} catch (FacebookApiException $e) {
		error_log($e);
	}
}

// login or logout url will be needed depending on current user state.
if ($me) {
	$logoutUrl = $facebook->getLogoutUrl();
} else {
	$loginUrl = $facebook->getLoginUrl(array(
	//'req_perms'       => 'publish_stream',
	//'next'       => APLICATION_URL,
	)
	);
	?>
	<script>
	window.parent.location = "<?php echo $loginUrl?>";
	//	window.parent.location = "https://www.facebook.com/login.php?api_key=<?php echo FB_API_ID?>&cancel_url=http://apps.facebook.com/gues_test/&display=page&fbconnect=1&next=<?php echo APLICATION_URL?>&return_session=1&session_version=3&v=1.0";
	</script>
	<?php
	exit;
}

//print_r($session);
//echo "<pre>";print_r($_REQUEST);exit;

//Post to my feed
//$attachment = array('message' => 'this is my message',
//'name' => 'This is my demo Facebook application!',
//'caption' => "Caption of the Post",
//'link' => 'http://mylink.com',
//'description' => 'this is a description',
//'picture' => 'http://www.realivent.com/listing_images/t_img479d2dccce0c7.jpg',
//'actions' => array(array('name' => 'Get Search',
//'link' => 'http://www.google.com'))
//);
//
//
//$result = $facebook->api('/me/feed/',
//'post',
//$attachment);

//Post to someone's wall
//$attachment = array('message' => 'this is my message',
//'name' => 'This is my demo Facebook application!',
//'caption' => "Caption of the Post",
//'link' => 'http://mylink.com',
//'description' => 'this is a description',
//'actions' => array(array('name' => 'Get Search',
//'link' => 'http://www.google.com'))
//);
//$result = $facebook->api('/677123482/feed/',
//'post',
//$attachment);
//print_r($result);

//Get Friends
//$result = $facebook->api('/me/friends/');print_r($result);exit;

//$result = $facebook->api('/511176969/picture');print_r($result);exit;


if(isset($_POST['submit'])) {

	$username='';
	$password='';
	if(isset($_POST['username']))
	$username = $_POST['username'];
	if(isset($_POST['password']))
	$password = md5($_POST['password']);

	if($username && $password)
	{
		include "../db/opendb.php";
		$query = "select Verified, Role, Password, ID from Users where Username='".$username."'";
		//echo $query;
		$result = mysql_query($query) or die ("SQL Error".mysql_error());
		$row=mysql_fetch_assoc($result);
		if(!$row['Password'] || $row['Password'] !=$password)
		{
			$err_msg = "The login information you have supplied is incorrect! <br> Please try again!";
			//include "information.php";
		}
		else if($row['Verified'] != '1')
		{
			$err_msg = "This user account is not verified! <br> Please try again!";
		}
		else
		{
			$_SESSION['username']=$username;
			$_SESSION['role']=$row["Role"];
			$user_id = $_SESSION['id']=$row["ID"];
			//set the type session variable : basic/single/starter/pro/power
			$query = "select Type from Users where Username='".$username."'";
			//echo $query;
			$result = mysql_query($query) or die ("SQL Error".mysql_error());
			$row=mysql_fetch_assoc($result);
			$_SESSION['type']=$row['Type'];

			//Now check if user has fb user id on our main application
			$signed_request = $_REQUEST["signed_request"];
			list($encoded_sig, $payload) = explode('.', $signed_request, 2);
			$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
			//echo "<pre>";print_r($data);exit;
			$fb_signed_id = $data['user_id'];

			$sql = "SELECT * FROM facebook_user_map WHERE fb_signed_id='$fb_signed_id'";
			$rs = mysql_query($sql);
			if(mysql_num_rows($rs) < 1) {
				//add id
				$sql = "INSERT IGNORE INTO facebook_user_map (user_id, fb_signed_id) VALUES ('$user_id','$fb_signed_id')";
				$rs = mysql_query($sql);
			}
			header("location:index.php?login=success");
			exit;
		}
	}
}

$section = "login.php";
if(isset($_SESSION['username'])) {
	$section = "login.php";
//	$section = "home.php";
}

?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
  <head>
    <title>Realivent.com</title>
    <link type="text/css" rel="stylesheet" href="<?php echo CANVAS_URL?>/style/style.css" />
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
	FB.init({
		appId   : '<?php echo $facebook->getAppId(); ?>',
		session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
		status  : true, // check login status
		cookie  : true, // enable cookies to allow the server to access the session
		xfbml   : true // parse XFBML
	});

	// whenever the user logs in, we refresh the page
	FB.Event.subscribe('auth.login', function() {
		window.location.reload();
	});
};

(function() {
	var e = document.createElement('script');
	e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
	e.async = true;
	document.getElementById('fb-root').appendChild(e);
}());

function fb_publish(image_url, title, url, description, price) {
	FB.ui(
	{
		method: 'stream.publish',
		message: title,
		attachment: {
			name: title,
			caption: "<b>Price:</b> $"+price,
			media: [
			{
			"type": "image",
			"src": image_url,
			"href": url
			}]
			,
			description: (
			description
			),
			href: url
		},
		action_links: [
		{ text: 'View Property', href: url }
		],
		user_prompt_message: 'Personal message here'
	},
	function(response) {
		if (response && response.post_id) {
			alert('Post was published.');
		} else {
			alert('Post was not published.');
		}
	}
	);
}
</script>
<div class="main_container">

<?php if($err_msg) { ?>
<div class="UIMessageBox error" id="error"><p id="standard_explanation" class="sub_message"><strong><?php echo $err_msg?></p></div><br>
<?php } ?>
<?php
include($section);
?>
</div>
  </body>
</html>
